import taskService, {
	type TaskItem,
	type TaskField,
} from "@/api/services/taskService";
import { IconButton, Iconify } from "@/components/icon";
import {
	MinusCircleOutlined,
	PlusOutlined,
	SearchOutlined,
} from "@ant-design/icons";
import {
	Button,
	Card,
	Empty,
	Form,
	Input,
	Modal,
	Space,
	Table,
	Tag,
	Typography,
	message,
	Pagination,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import parse from "html-react-parser";
import { useEffect, useState, useCallback } from "react";
import { useLocation } from "react-router-dom";
import "./index.less";

const TaskPage = () => {
	const [loading, setLoading] = useState(false);
	const [taskList, setTaskList] = useState<TaskItem[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [keyword, setKeyword] = useState("");
	const [searched, setSearched] = useState(false);
	const [detailVisible, setDetailVisible] = useState(false);
	const [currentTask, setCurrentTask] = useState<TaskItem>();
	const [form] = Form.useForm();

	const [queryParams, setQueryParams] = useState({
		current: 1,
		pageSize: 10,
		keyword: "",
	});

	const fetchTaskList = async (params: any) => {
		try {
			if (!params.keyword.trim()) {
				setTaskList([]);
				setTotal(0);
				setSearched(false);
				return;
			}

			setLoading(true);
			const res = await taskService.taskList({
				...params,
				current: params.current || currentPage,
				pageSize: params.pageSize || pageSize,
			});
			setTaskList(res.items);
			setTotal(res.total);
			setSearched(true);
		} catch (error) {
			message.error("获取任务列表失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchTaskList(queryParams);
	}, [queryParams]);

	const handleSubmit = async () => {
		if (!currentTask) return;

		try {
			const values = await form.validateFields();

			// 转换字段格式
			const formList = values.formList || [{}];
			const submitData = formList.map((item) => {
				const fields = {};
				Object.entries(item.fields || {}).forEach(([id, value]) => {
					fields[id] = {
						field_id: Number(id),
						value: value,
					};
				});

				return {
					task_id: currentTask.id,
					fields,
				};
			});

			// 批量提交
			await Promise.all(submitData.map((data) => taskService.taskSubmit(data)));
			message.success("任务提交成功");
			setDetailVisible(false);
			form.resetFields();

			// 刷新列表
			fetchTaskList(queryParams);
		} catch (error: any) {
			if (error.errorFields) {
				message.error("请填写必填项");
			} else {
				message.error("任务提交失败");
			}
		}
	};

	const handleViewDetail = async (task: TaskItem) => {
		try {
			const detail = await taskService.taskInfo(task.id);
			setCurrentTask(detail);
			setDetailVisible(true);
			form.resetFields();
		} catch (error) {
			message.error("获取任务详情失败");
		}
	};

	const renderFormItem = (field: TaskField) => {
		switch (field.fieldType) {
			case "text":
			case "textarea":
				return (
					<Form.Item
						key={field.fieldId}
						name={["fields", field.fieldId.toString()]}
						label={field.fieldLabel}
						rules={[
							{
								required: field.required,
								message: `请输入${field.fieldLabel}`,
							},
						]}
					>
						{field.fieldType === "textarea" ? (
							<Input.TextArea
								placeholder={field.placeholder || `请输入${field.fieldLabel}`}
								rows={4}
							/>
						) : (
							<Input
								placeholder={field.placeholder || `请输入${field.fieldLabel}`}
							/>
						)}
					</Form.Item>
				);
			default:
				return null;
		}
	};

	const renderFormFields = (fields: TaskField[], fieldListName: number) => {
		return fields.map((field) => {
			switch (field.fieldType) {
				case "text":
				case "textarea":
					return (
						<Form.Item
							key={field.fieldId}
							name={[fieldListName, "fields", field.fieldId.toString()]}
							label={field.fieldLabel}
							rules={[
								{
									required: field.required,
									message: `请输入${field.fieldLabel}`,
								},
							]}
						>
							{field.fieldType === "textarea" ? (
								<Input.TextArea
									placeholder={field.placeholder || `请输入${field.fieldLabel}`}
									rows={4}
								/>
							) : (
								<Input
									placeholder={field.placeholder || `请输入${field.fieldLabel}`}
								/>
							)}
						</Form.Item>
					);
				default:
					return null;
			}
		});
	};

	const columns: ColumnsType<TaskItem> = [
		{
			title: "ID",
			dataIndex: "id",
			width: 80,
			align: "center",
		},
		{
			title: "标题",
			dataIndex: "title",
			ellipsis: true,
			render: (text) => (
				<Typography.Text
					style={{
						fontSize: "15px",
						fontWeight: 500,
					}}
				>
					{text}
				</Typography.Text>
			),
		},
		{
			title: "分类",
			dataIndex: ["category", "name"],
			width: 120,
			align: "center",
			render: (text) => (
				<Tag color="cyan" icon={<Iconify icon="material-symbols:category" />}>
					{text}
				</Tag>
			),
		},
		{
			title: "价格",
			dataIndex: "price",
			width: 100,
			align: "center",
			render: (price) => (
				<Typography.Text type="success" strong>
					￥{price}
				</Typography.Text>
			),
		},
		{
			title: "状态",
			dataIndex: "status_text",
			width: 100,
			align: "center",
			render: (status_text, record) => (
				<Tag
					color={record.status === 1 ? "success" : "default"}
					icon={
						<Iconify
							icon={
								record.status === 1
									? "material-symbols:check-circle"
									: "material-symbols:pending"
							}
						/>
					}
				>
					{status_text}
				</Tag>
			),
		},
		{
			title: "操作",
			key: "action",
			width: 100,
			align: "center",
			render: (_, record) => (
				<Button
					type="primary"
					size="small"
					onClick={(e) => {
						e.stopPropagation();
						handleViewDetail(record);
					}}
					icon={<Iconify icon="material-symbols:assignment" />}
					style={{
						borderRadius: "15px",
						padding: "0 16px",
					}}
				>
					提交
				</Button>
			),
		},
	];

	const handleSearch = (value: string) => {
		setQueryParams({
			...queryParams,
			keyword: value,
			current: 1,
		});
	};

	const handlePageChange = (page: number, size: number) => {
		setQueryParams({
			...queryParams,
			current: page,
			pageSize: size,
		});
	};

	const resetPageState = useCallback(() => {
		setQueryParams({
			current: 1,
			pageSize: 10,
			keyword: "",
		});
		setCurrentPage(1);
		setPageSize(10);
		setKeyword("");
		setLoading(false);
	}, []);

	const refreshList = useCallback(() => {
		setQueryParams((prev) => ({ ...prev }));
	}, []);

	const location = useLocation();

	useEffect(() => {
		resetPageState();
	}, [location.pathname]);

	useEffect(() => {
		setCurrentPage(queryParams.current);
		setPageSize(queryParams.pageSize);
		setKeyword(queryParams.keyword);
	}, [queryParams]);

	return (
		<Card className="task-page-container" bordered={false}>
			<Space direction="vertical" size="large" style={{ width: "100%" }}>
				<div
					className="search-container"
					style={{
						background: "linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)",
						padding: "20px",
						borderRadius: "12px",
						boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
					}}
				>
					<Input
						placeholder="搜索你感兴趣的任务..."
						value={keyword}
						onChange={(e) => setKeyword(e.target.value)}
						style={{
							width: "100%",
							maxWidth: "500px",
							height: "44px",
							borderRadius: "22px",
						}}
						prefix={<SearchOutlined style={{ color: "#1890ff" }} />}
						allowClear
						onPressEnter={() => {
							setQueryParams({ ...queryParams, keyword, current: 1 });
						}}
					/>
					<Button
						type="primary"
						onClick={() => {
							setQueryParams({ ...queryParams, keyword, current: 1 });
						}}
						style={{
							marginLeft: "12px",
							height: "44px",
							borderRadius: "22px",
							padding: "0 24px",
						}}
					>
						搜索
					</Button>
				</div>

				{!searched ? (
					<Empty
						description={
							<div style={{ color: "#666" }}>
								<p>还没有搜索任何内容</p>
								<small>输入关键词开始寻找感兴趣的任务吧</small>
							</div>
						}
						image={Empty.PRESENTED_IMAGE_SIMPLE}
					/>
				) : (
					<>
						<div className="task-cards-container">
							{taskList.map((task) => (
								<Card
									key={task.id}
									className="task-card"
									onClick={() => handleViewDetail(task)}
								>
									<Typography.Title level={4} className="task-title">
										{task.title}
									</Typography.Title>

									<div className="task-meta">
										<div className="meta-item">
											<Iconify
												icon="material-symbols:category"
												style={{ fontSize: "20px" }}
											/>
											<Tag color="cyan" style={{ padding: "4px 12px" }}>
												{task.category?.name}
											</Tag>
										</div>
										<div className="meta-item">
											<Iconify
												icon="material-symbols:payments"
												style={{ fontSize: "20px" }}
											/>
											<Typography.Text
												type="success"
												strong
												style={{ fontSize: "16px" }}
											>
												￥{task.price}
											</Typography.Text>
										</div>
										<div className="meta-item">
											<Iconify
												icon={
													task.status === 1
														? "material-symbols:check-circle"
														: "material-symbols:pending"
												}
												style={{ fontSize: "20px" }}
											/>
											<Tag
												color={task.status === 1 ? "success" : "default"}
												style={{ padding: "4px 12px" }}
											>
												{task.status_text}
											</Tag>
										</div>
									</div>

									<div className="task-footer">
										<Space>
											<Iconify
												icon="material-symbols:update"
												style={{ fontSize: "16px" }}
											/>
											<Typography.Text type="secondary">
												更新时间：
												{dayjs(task.updatetime * 1000).format(
													"YYYY-MM-DD HH:mm",
												)}
											</Typography.Text>
										</Space>
										<Button
											type="primary"
											size="middle"
											onClick={(e) => {
												e.stopPropagation();
												handleViewDetail(task);
											}}
											icon={<Iconify icon="material-symbols:assignment" />}
											style={{
												borderRadius: "20px",
												padding: "4px 20px",
												height: "36px",
											}}
										>
											提交任务
										</Button>
									</div>
								</Card>
							))}
						</div>
						<Pagination
							current={queryParams.current}
							pageSize={queryParams.pageSize}
							total={total}
							onChange={handlePageChange}
							showSizeChanger
							showQuickJumper
							showTotal={(total) => `共 ${total} 条任务`}
							style={{ marginTop: "24px", textAlign: "center" }}
						/>
					</>
				)}
			</Space>
		</Card>
	);
};

export default TaskPage;
